<template>
	<a-modal v-bind="options" class="bill-batch-handle-dialog">
		<div class="tips">
			<div>
				共选中
				<strong v-color="{color: 'primary'}">{{ bills.length }}</strong>
				条账单
			</div>
			<a-divider type="vertical" />
			<div>
				<a-typography-text type="secondary">收款</a-typography-text>
				<strong v-color="{color: 'primary'}">+{{ sum.in.toLocaleString() }} 元</strong>
			</div>
			<a-divider type="vertical" />
			<div>
				<a-typography-text type="secondary">付款</a-typography-text>
				<strong v-color="{color: 'danger'}">{{ sum.out.toLocaleString() }} 元</strong>
			</div>
			<a-divider type="vertical" />
			<div>
				<a-typography-text type="secondary">合计</a-typography-text>
				<strong>{{ sum.total.toLocaleString() }} 元</strong>
			</div>
		</div>
		<a-typography-paragraph strong>
			<blockquote>完善收（付）款信息</blockquote>
		</a-typography-paragraph>
		<a-form ref="formRef" :model="entity">
			<a-row :gutter="24">
				<a-col :span="10">
					<a-form-item label="支付时间" name="practicalTime" :rules="[{required: true, message: '请选择支付时间'}]">
						<a-date-picker
							v-model:value="entity.practicalTime"
							show-time
							:value-format="DATE_FORMAT.DATETIME"
							:disabled-date="disabledDate"
							:disabled-time="disabledTime"
							style="width: 100%" />
					</a-form-item>
				</a-col>
				<a-col :span="14">
					<a-form-item label="支付方式" name="paymentMethod" :rules="[{required: true, message: '请选择支付方式'}]">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select
									v-model:value="entity.paymentMethod"
									:options="paymentMethods"
									:field-names="DEFAULT_FIELD_NAME"
									placeholder="支付方式"
									style="width: 120px" />
								<a-input v-model:value="entity.paymentAccount" placeholder="请输入客户账号" style="flex: 1" />
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
			</a-row>
			<a-form-item label="支付流水号" name="bankStatement">
				<a-input v-model:value="entity.bankStatement" show-count :maxlength="100" placeholder="请输入支付流水号" />
			</a-form-item>
			<a-form-item label="支付备注" name="comment">
				<a-textarea v-model:value="entity.comment" show-count :maxlength="200" placeholder="请输入支付备注" />
			</a-form-item>
			<a-form-item label="支付凭证" name="fileIds">
				<file-upload v-model:files="files" show-qr-code show-tips :file-size="5" />
			</a-form-item>
		</a-form>
	</a-modal>
</template>

<script setup lang="ts">
	import {computed, reactive, ref, toRef, watchEffect} from 'vue'
	import {FormInstance, message} from 'ant-design-vue'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import {Img} from 'yuxin-base/src/types'
	import {DEFAULT_FIELD_NAME, DIC_PID_MAP} from 'yuxin-base/src/constant'
	import {financeBillAffirmFinanceBatch, affirmFinanceForDetails} from '@/api/bill'
	import DATE_FORMAT, {nowDateTime} from 'yuxin-base/src/utils/date'
	import dayjs, {Dayjs} from 'dayjs'
	import {range} from 'xe-utils'
	import FileUpload from '@/components/common/file-upload.vue'

	const props = defineProps<{
		visible: boolean
		bills: any[]
		type?: string
		extraParams?: any
	}>()

	const formRef = ref<FormInstance>()
	const emits = defineEmits(['update:visible', 'close'])
	const options = reactive({
		title: '批量处理',
		width: 1000,
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		confirmLoading: false,
		visible: toRef(props, 'visible'),
		onOk() {
			formRef.value?.validate().then(() => {
				if (props.type === 'enterContract') {
					enterContract()
					return
				}
				const {extraParams, bills} = props
				entity.fileIds = files.value.map(o => o.id)
				entity.billIdList = extraParams ? bills : props.bills.map(o => o.id)

				options.confirmLoading = true
				financeBillAffirmFinanceBatch(entity)
					.then(res => {
						options.onCancel()
						message.success('操作成功')
					})
					.finally(() => (options.confirmLoading = false))
			})
		},
		onCancel() {
			emits('update:visible', false)
			setTimeout(() => emits('close'), 100)
			formRef.value?.resetFields()
			entity.paymentAccount = null
		}
	})

	const entity = reactive<any>({
		// 账单ID集合
		billIdList: [],
		// 费用备注
		comment: null,
		// 交易流水
		bankStatement: null,
		// 收付款方式途径【字典】
		paymentMethod: null,
		// 收款账户
		paymentAccount: null,
		// 实收付时间
		practicalTime: null,
		// 支付凭证附件
		fileIds: []
	})

	const files = ref<Img[]>([])

	const sum = computed(() => {
		const {extraParams, bills} = props
		const amounts = extraParams ? extraParams.notOccurredMoney : props.bills.map(o => o.notOccurredMoney)

		// 因为账单明细和账单金额正负不一样 明细需要根据feeDirection判断正负 o.feeDirection == 1 为正
		if (props.type === 'enterContract' && !extraParams) {
			const straight = props.bills.filter(o => o.feeDirection == 1)
			const burden = props.bills.filter(o => o.feeDirection != 1)

			let straightSum = Number(
				straight
					.map(o => o.notOccurredMoney)
					.reduce((per, curr) => per + curr, 0)
					.toFixed(2)
			)

			let burdenSum = Number(
				burden
					.map(o => o.notOccurredMoney)
					.reduce((per, curr) => per - curr, 0)
					.toFixed(2)
			)

			return {
				in: straightSum,
				out: burdenSum,
				total: Number((straightSum + burdenSum).toFixed(2))
			}
		}
		if (extraParams) {
			const {notOccurredMoney, isIncome} = extraParams
			return {
				in: isIncome ? notOccurredMoney : 0,
				out: !isIncome ? notOccurredMoney : 0,
				total: notOccurredMoney * (isIncome ? 1 : -1)
			}
		}

		return {
			in: Number(
				amounts
					.filter(num => num > 0)
					.reduce((per, curr) => per + curr, 0)
					.toFixed(2)
			),
			out: Number(
				amounts
					.filter(num => num < 0)
					.reduce((per, curr) => per + curr, 0)
					.toFixed(2)
			),
			total: Number(amounts.reduce((per, curr) => per + curr, 0).toFixed(2))
		}
	})

	const disabledDate = (current: Dayjs) => {
		return current && current > dayjs()
	}

	const disabledTime = () => {
		const now = dayjs()

		return {
			disabledHours: () => range(0, 24).filter(o => o > now.hour()),
			disabledMinutes: () => range(0, 60).filter(o => o > now.minute()),
			disabledSeconds: () => range(0, 60).filter(o => o > now.second())
		}
	}

	const paymentMethods = ref<any[]>([])

	const enterContract = () => {
		entity.detailList = props.bills.map(o => {
			return {
				billDetailId: o.id
			}
		})
		options.confirmLoading = true
		affirmFinanceForDetails(entity)
			.then(res => {
				options.onCancel()
				message.success('操作成功')
			})
			.finally(() => (options.confirmLoading = false))
	}

	watchEffect(() => {
		if (props.visible) {
			// 默认支付时间为当前时间
			entity.practicalTime = nowDateTime()
			settingApi.getDicListByPid(DIC_PID_MAP['PAYMENTMETHOD@PAYMENTMETHOD']).then(({data}) => (paymentMethods.value = data))
		}
	})
</script>

<style lang="less">
	.bill-batch-handle-dialog {
		.ant-modal-body {
			.ant-form-item-label {
				width: 110px;
			}

			.tips {
				display: flex;
				background: #e5efff;
				padding: 12px 16px;
				align-items: center;

				> div:not(.ant-divider) {
					flex: 1;

					&:not(:first-child) {
						display: flex;
						justify-content: space-between;
					}
				}
			}
		}
	}
</style>
